import * as React from 'react';
import classNames from 'classnames';
import { useState } from 'react'

export interface SwitchProps {
	children?: React.ReactNode;
	className?: string;

	checked?: boolean;
	defaultChecked?: boolean;

	disabled?: boolean;

	size?: string;

	loading?: boolean;

	checkedChildren?: React.ReactNode;
	unCheckedChildren?: React.ReactNode;

	onChange?: (checked: boolean, e: React.MouseEvent<HTMLElement>) => void;
	onClick?: (checked: boolean, e: React.MouseEvent<HTMLElement>) => void;
}

const Switch: React.FC<SwitchProps> = props => {
	const prefixCls = 'bh-switch';
	const {
		children,
		className,

		checked = false,
		defaultChecked = false,

		disabled = false,

		size,

		loading = false,

		checkedChildren,
		unCheckedChildren,

		onChange,
		onClick,
		...restProps
	} = props;
	const [newChecked, setNewChecked] = useState(defaultChecked);
	const classString = classNames(
		prefixCls,
		className,
		{
			[`${prefixCls}-checked`]: newChecked,
			[`${prefixCls}-disabled`]: disabled || loading,
			[`${prefixCls}-small`]: size == 'small',
		}
	);

	const onInternalClick = (e: React.MouseEvent<HTMLElement>) => {
		if(disabled || loading) {
			return;
		}
		let newVal = !newChecked;
		setNewChecked(newVal);
		onChange && onChange(newVal, e);
		onClick && onClick(newVal, e);
	}
	const renderInterChildren = () => {
		if(newChecked && checkedChildren) {
			return (checkedChildren);
		}if(!newChecked && unCheckedChildren) {
			return (unCheckedChildren);
		}
		return null;
	};

	return (
		<button type='button' {...restProps} className={classString} onClick={onInternalClick}>
		    <div className="bh-switch-inner">{renderInterChildren()}</div>
		    <div className="bh-switch-handle">
		    	{loading && <i className="bh-switch-loading-icon bh-icon bh-icon-loading"></i>}
		    </div>
		</button>
	)
};

export default Switch;